package com.zhike.service.messages.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import com.zhike.common.enums.YesNoEnum;
import com.zhike.common.repository.ACKMessage;
import com.zhike.common.repository.ClearMessage;
import com.zhike.common.repository.HistoryMessage;
import com.zhike.service.messages.IACKMessageRepository;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ACKMessageRepository implements IACKMessageRepository {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public void saveAckMessageSingle(String messageId, String fromUid, String toUid) throws Exception {

        ACKMessage ack = new ACKMessage();
        ack.setId(messageId);
        ack.setFromUid(fromUid);
        ack.setToUid(toUid);
        ack.setIfAck(YesNoEnum.NO.getValue());
        mongoTemplate.insert(ack);
        log.info("保存ACK ---");

    }

    public void saveAckMessageForGroup(String messageId, String fromUid, String groupId) {
        try {
            ACKMessage ack = new ACKMessage();
            ack.setId(messageId);
            ack.setFromUid(fromUid);
            ack.setGroupId(groupId);
            ack.setIfAck(YesNoEnum.NO.getValue());
            mongoTemplate.insert(ack);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<ACKMessage> findAckMessage(String fromUid, String toUid) {
        Query query = new Query(Criteria.where("fromUid").is(fromUid).and("toUid").is(toUid));
        return mongoTemplate.find(query, ACKMessage.class);
    }

    public ACKMessage findAckMessageForGroup(String groupId, String fromUid) {
        Query query = new Query(Criteria.where("fromUid").is(fromUid).and("groupId").is(groupId));
        return mongoTemplate.findOne(query, ACKMessage.class);
    }

    public void deleteAckMessage(String fromUid, String toUid) {
        Query query = new Query(Criteria.where("fromUid").is(fromUid).and("toUid").is(toUid));
        mongoTemplate.remove(query, ACKMessage.class);
    }

    public long unreadCount(String fromUid, String toUid) throws Exception {
        Query query = new Query(Criteria.where("fromUid").is(fromUid)
                .and("toUid").is(toUid));
        return mongoTemplate.count(query, ACKMessage.class);
    }

    @Override
    public void batchSaveAckMessageSingle(List<HistoryMessage> hms) throws Exception {
        for (HistoryMessage hm : hms) {
            saveAckMessageForGroup(hm.getId(), hm.getSenderUid(), hm.getReceiver());
        }
    }
}
